import { createPinia } from 'pinia';
/*
 * @Author: zhangfeng
 * @Date: 2023-12-12 16:35:45
 * @LastEditTime: 2024-02-01 17:28:25
 * @LastEditors: zhangfeng
 * @Description:
 * @FilePath: \manager\managersystem\src\permission.ts
 * © 2023 张峰，All rights reserved.
 */
import router from './router';
import { user, userInfo, menusList } from './store/index';
import { getUserInfo } from './api/login';

import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

NProgress.configure({ showSpinner: false });
const loginRoutePath = '/login';
const defaultRoutePath = '/home';

router.beforeEach(async (to, from, next) => {
	NProgress.start();

	const storeUserInfo = userInfo();
	const storemenusList = menusList();
	// 此路由需要授权
	// if (!to.meta.requiresAuth) {
	// 是否登录
	if (user().token) {
		// 是否有跳转路径(已经登录后，就去首页) 默认去首页
		if (to.path === loginRoutePath || to.path === '/') {
			next({ path: defaultRoutePath });
		} else {
			// 查看是否有用户信息，没有需要重新获取
			if (!storeUserInfo.uerInfoRoleId) {
				await getUserInfo().then(async (res: AxiosResponse<GetuserInfo>) => {
					const { menus, ...result } = res.result;
					await storemenusList.saveMenusList(menus);
					await storeUserInfo.saveInformation(result);

					await next(to);
				});
			} else {
				await next();
			}
		}
	}
	// 未登录 跳登录页登录
	else {
		console.log(1);
		// router.push({ path: '/login' });
		console.log(to);
		if (to.path == '/login') {
			NProgress.done();
			next();
		} else {
			NProgress.done();
			next(`/login?redirect=${to.fullPath}`);
		}
		// router.push({ path: '/login' });
	}
	// } else {
	// 	next();
	// }
});

router.afterEach(() => {
	NProgress.done(); // finish progress bar
});
